# __author: Rachel章
# data: 2023/4/28
# desc:契望成token工具类
import os
import time

import requests

from common.config import getconf
from common.yaml_util import read_yaml, write_yaml

phones = ["13000000000", "16000000001","13524982440"]

def get_code(env, phone):
    """获取验证码"""
    headers = {"content-type": "application/json"}
    Host = getconf(env, "qwc_url") + "flashmall-supplier-server"
    url = Host + "/v1/login/getCode"
    data2 = {
        "phone": phone,
        "codeType": 1
    }
    respons = requests.post(url, json=data2, headers=headers).json()
    print(respons)
    return respons


def by_code(env, phone):
    """验证码登录"""
    headers = {"content-type": "application/json"}
    Host = getconf(env, "qwc_url") + "flashmall-supplier-server"
    url = Host + "/v1/login/byCode"
    data2 = {
        "phone": phone,
        "msgCode": "666666",
        "saveDays": 3
    }
    respons = requests.post(url, json=data2, headers=headers)
    cookies = respons.cookies.get_dict()
    # print(respons.json())
    if respons.json()['code'] == '0':
        return cookies["ticketKey"]
    else:
        return ""


def set_cookie(env):
    """多个供应商cookie批量写入"""
    for p in phones:
        respons = get_code(env, p)
        # if respons['code']=='1000009006':
        #     return 0
        # else:
        write_yaml("/data/supplier_" + p + ".yaml", {"ticketKey": by_code(env, p)})


def read_cookie(phone):
    ticketKey = read_yaml("/data/supplier_" + phone + ".yaml", "ticketKey")
    # print("ticketKey:%s" % ticketKey)
    dict = {'ticketKey': ticketKey}
    return dict

class QwcCookieUtil:
    @staticmethod
    def get_c(env,p):
        # print('契望成供应商登录cookie写入')
        try:
            cokkie = read_cookie(p)
            # print(read_cookie(p))
            return cokkie
        except Exception as e:
            print(e)
            set_cookie(env)
            # print('契望成供应商登录cookie写入结束')
            return read_cookie(p)

if __name__ == '__main__':
    # print(QwcCookieUtil.get_c("test","13000000000"))
    now = str(time.time()).replace(".", "")[0:11]
    print("now:" + now)
